/**
 * 响应数据解析工具类
 * 统一处理API响应数据的解析，避免在各个模块中重复编写解析逻辑
 */

export interface ParsedListResponse<T> {
  items: T[]
  total: number
  page?: number
  size?: number
  pagination?: {
    total: number
    page: number
    size: number
    pages: number
    has_prev: boolean
    has_next: boolean
  }
}

export interface ParsedResponse<T> {
  data: T
  success: boolean
  message?: string
  code?: number
}

export interface ParsedCountResponse {
  count: number
  total: number
  success: boolean
  message?: string
}

export interface ParsedStatsResponse<T> {
  stats: T
  success: boolean
  message?: string
}

/**
 * 响应数据解析器
 */
export class ResponseParser {
  /**
   * 解析列表响应数据
   * 支持多种后端响应格式的自动识别和解析
   * 
   * @param response - API响应对象
   * @returns 标准化的列表数据格式
   */
  static parseListResponse<T>(response: any): ParsedListResponse<T> {
    let items: T[] = []
    let total = 0
    let page = 1
    let size = 10
    let pagination: any = null

    try {
      // 处理axios响应包装
      const data = response?.data || response

      // 格式1: 标准成功响应格式 { success: true, code: 200, data: [...], pagination: {...} }
      if (data?.success === true && data?.data) {
        if (Array.isArray(data.data)) {
          // 直接数组格式
          items = data.data
          total = data.pagination?.total || items.length
          page = data.pagination?.page || 1
          size = data.pagination?.size || items.length
          pagination = data.pagination
        } else if (data.data.items && Array.isArray(data.data.items)) {
          // 嵌套items格式
          items = data.data.items
          total = data.data.total || data.data.pagination?.total || items.length
          page = data.data.page || data.data.pagination?.page || 1
          size = data.data.size || data.data.pagination?.size || items.length
          pagination = data.data.pagination || data.pagination
        }
      }
      // 格式2: 直接数组格式 { data: [...] }
      else if (data?.data && Array.isArray(data.data)) {
        items = data.data
        total = data.total || data.pagination?.total || items.length
        page = data.page || data.pagination?.page || 1
        size = data.size || data.pagination?.size || items.length
        pagination = data.pagination
      }
      // 格式3: items包装格式 { data: { items: [...], total: number } }
      else if (data?.data?.items && Array.isArray(data.data.items)) {
        items = data.data.items
        total = data.data.total || data.data.pagination?.total || items.length
        page = data.data.page || data.data.pagination?.page || 1
        size = data.data.size || data.data.pagination?.size || items.length
        pagination = data.data.pagination
      }
      // 格式4: 嵌套success响应格式 { data: { success: true, data: [...] } }
      else if (data?.data?.success === true && data?.data?.data) {
        if (Array.isArray(data.data.data)) {
          items = data.data.data
          total = data.data.pagination?.total || items.length
          page = data.data.pagination?.page || 1
          size = data.data.pagination?.size || items.length
          pagination = data.data.pagination
        } else if (data.data.data.items && Array.isArray(data.data.data.items)) {
          items = data.data.data.items
          total = data.data.data.total || data.data.data.pagination?.total || items.length
          page = data.data.data.page || data.data.data.pagination?.page || 1
          size = data.data.data.size || data.data.data.pagination?.size || items.length
          pagination = data.data.data.pagination
        }
      }
      // 格式5: 直接是数组
      else if (Array.isArray(data)) {
        items = data
        const topLevelPagination =
          response?.pagination ||
          (response?.data && !Array.isArray(response.data) ? (response.data as any)?.pagination : undefined)
        total =
          topLevelPagination?.total ??
          response?.total ??
          response?.data?.total ??
          items.length
        page =
          topLevelPagination?.page ??
          response?.page ??
          response?.data?.page ??
          1
        size =
          topLevelPagination?.size ??
          response?.size ??
          response?.data?.size ??
          items.length
        pagination = topLevelPagination ?? response?.pagination ?? response?.data?.pagination ?? null
      }
      // 格式6: 顶层items格式 { items: [...], total: number }
      else if (data?.items && Array.isArray(data.items)) {
        items = data.items
        total = data.total || items.length
        page = data.page || 1
        size = data.size || items.length
        pagination = data.pagination
      }
      // 格式7: 用户列表特殊格式 { users: [...], total: number, page: number, size: number, pages: number, has_prev: boolean, has_next: boolean }
      else if (data?.users && Array.isArray(data.users)) {
        items = data.users
        total = data.total || items.length
        page = data.page || 1
        size = data.size || items.length
        pagination = {
          total: data.total || items.length,
          page: data.page || 1,
          size: data.size || items.length,
          pages: data.pages || Math.ceil((data.total || items.length) / (data.size || items.length)),
          has_prev: data.has_prev || false,
          has_next: data.has_next || false
        }
      }

      return {
        items,
        total,
        page,
        size,
        pagination
      }
    } catch (error) {
      // 解析失败时只记录错误，不输出详细信息
      if (import.meta.env.DEV) {
      console.error('ResponseParser.parseListResponse - 解析失败:', error)
      }
      return {
        items: [],
        total: 0,
        page: 1,
        size: 10
      }
    }
  }

  /**
   * 解析单个数据响应
   * 
   * @param response - API响应对象
   * @returns 标准化的单个数据格式
   */
  static parseResponse<T>(response: any): ParsedResponse<T> {
    try {
      // 处理axios响应包装
      const data = response?.data || response

      // 标准成功响应格式
      if (data?.success === true) {
        return {
          data: data.data,
          success: true,
          message: data.message,
          code: data.code
        }
      }

      // 嵌套success响应格式
      if (data?.data?.success === true) {
        return {
          data: data.data.data,
          success: true,
          message: data.data.message,
          code: data.data.code
        }
      }

      // 直接数据格式
      if (data?.data) {
        return {
          data: data.data,
          success: true,
          message: data.message
        }
      }

      // 直接返回数据
      return {
        data: data,
        success: true
      }
    } catch (error) {
      // 解析失败时只记录错误
      if (import.meta.env.DEV) {
      console.error('ResponseParser.parseResponse - 解析失败:', error)
      }
      return {
        data: null as T,
        success: false,
        message: '数据解析失败'
      }
    }
  }

  /**
   * 解析计数响应数据
   * 
   * @param response - API响应对象
   * @returns 标准化的计数数据格式
   */
  static parseCountResponse(response: any): ParsedCountResponse {
    try {
      const data = response?.data || response
      
      // 标准成功响应格式
      if (data?.success === true && data?.data) {
        return {
          count: data.data.count || data.data.total || 0,
          total: data.data.total || data.data.count || 0,
          success: true,
          message: data.message
        }
      }
      
      // 直接数据格式
      if (data?.data) {
        return {
          count: data.data.count || data.data.total || data.data || 0,
          total: data.data.total || data.data.count || data.data || 0,
          success: true
        }
      }
      
      // 直接数字格式
      if (typeof data === 'number') {
        return {
          count: data,
          total: data,
          success: true
        }
      }
      
      // 包含count字段的对象
      if (data?.count !== undefined || data?.total !== undefined) {
        return {
          count: data.count || data.total || 0,
          total: data.total || data.count || 0,
          success: true
        }
      }
      
      return {
        count: 0,
        total: 0,
        success: false,
        message: '无法解析计数数据'
      }
    } catch (error) {
      // 解析失败时只记录错误
      if (import.meta.env.DEV) {
      console.error('ResponseParser.parseCountResponse - 解析失败:', error)
      }
      return {
        count: 0,
        total: 0,
        success: false,
        message: '计数数据解析失败'
      }
    }
  }

  /**
   * 解析统计数据响应
   * 
   * @param response - API响应对象
   * @returns 标准化的统计数据格式
   */
  static parseStatsResponse<T>(response: any): ParsedStatsResponse<T> {
    try {
      const data = response?.data || response
      
      // 标准成功响应格式
      if (data?.success === true && data?.data) {
        return {
          stats: data.data,
          success: true,
          message: data.message
        }
      }
      
      // 直接数据格式
      if (data?.data) {
        return {
          stats: data.data,
          success: true
        }
      }
      
      // 检查是否为状态统计数据（包含数字字段）
      if (data && typeof data === 'object') {
        const hasNumericFields = Object.values(data).some(value => typeof value === 'number')
        if (hasNumericFields) {
          return {
            stats: data,
            success: true
          }
        }
      }
      
      // 直接返回数据
      return {
        stats: data,
        success: true
      }
    } catch (error) {
      // 解析失败时只记录错误
      if (import.meta.env.DEV) {
      console.error('ResponseParser.parseStatsResponse - 解析失败:', error)
      }
      return {
        stats: null as T,
        success: false,
        message: '统计数据解析失败'
      }
    }
  }

  /**
   * 解析用户列表响应
   * 专门处理用户数据的解析和标准化
   * 
   * @param response - API响应对象
   * @returns 标准化的用户列表数据
   */
  static parseUserListResponse(response: any): ParsedListResponse<any> {
    const result = this.parseListResponse(response)
    
    // 标准化用户数据格式
    result.items = result.items
      .filter((user: any) => user && user.id)
      .map((user: any) => ({
        id: user.id,
        name: user.name || user.username || user.real_name || `用户${user.id}`,
        username: user.username,
        email: user.email,
        real_name: user.real_name,
        status: user.status,
        roles: user.roles,
        department: user.department,
        position: user.position,
        phone: user.phone,
        avatar: user.avatar,
        created_at: user.created_at,
        updated_at: user.updated_at,
        last_login: user.last_login,
        login_count: user.login_count
      }))

    return result
  }

  /**
   * 解析项目列表响应
   * 专门处理项目数据的解析和标准化
   * 
   * @param response - API响应对象
   * @returns 标准化的项目列表数据
   */
  static parseProjectListResponse(response: any): { items: any[], total: number } {
    try {
      // 处理不同的响应格式
      let data = response
      
      // 如果响应有 data 属性，使用 data
      if (response && typeof response === 'object' && 'data' in response) {
        data = response.data
      }
      
      // 如果 data 还有 data 属性（嵌套结构），继续解析
      if (data && typeof data === 'object' && 'data' in data) {
        data = data.data
      }
      
      let items = []
      let total = 0
      
      // 处理项目列表数据
      if (data && typeof data === 'object') {
        // 检查是否有 items 或 projects 字段
        if (Array.isArray(data.items)) {
          items = data.items
          total = data.total || data.count || items.length
        } else if (Array.isArray(data.projects)) {
          items = data.projects
          total = data.total || data.count || items.length
        } else if (Array.isArray(data)) {
          // 如果 data 本身就是数组
          items = data
          total = items.length
        }
      }
      
      // 标准化项目数据
      const standardizedItems = items.map((item: any) => {
        const toStringId = (value: any) => {
          if (!value && value !== 0) return ''
          try {
            return typeof value === 'string' ? value : String(value)
          } catch {
            return ''
          }
        }
        const members = Array.isArray(item.members) ? item.members : []
        const ownerMember = members.find((member: any) => member?.role === 'owner')
        const managerMember = members.find((member: any) => member?.role === 'manager')
        const memberCount =
          typeof item.member_count === 'number'
            ? item.member_count
            : members.length
        const taskCount = item.task_count ?? item.tasks_count ?? 0
        const completedTaskCount = item.completed_task_count ?? item.completed_tasks ?? 0
        const requirementCount = item.requirement_count ?? 0
        const parseNumber = (value: any) => {
          if (typeof value === 'number') {
            return value
          }
          if (value === null || value === undefined || value === '') {
            return null
          }
          const parsed = Number(value)
          return Number.isFinite(parsed) ? parsed : null
        }
        const budget = parseNumber(item.budget)
        const estimatedHours = parseNumber(item.estimated_hours)
        const tags = Array.isArray(item.tags) ? item.tags : []
        const projectManagerRaw =
          item.project_manager ??
          ownerMember?.user_id ??
          managerMember?.user_id ??
          item.owner_id ??
          item.created_by
        const ownerIdRaw = ownerMember?.user_id ?? item.owner_id ?? item.created_by
        const projectManager = toStringId(projectManagerRaw)
        const ownerId = toStringId(ownerIdRaw)

        return {
          id: item.id || item._id,
          name: item.name || '',
          description: item.description || '',
          status: item.status || 'planning',
          priority: item.priority || 'medium',
          category: item.category || 'other',
          progress: item.progress || 0,
          task_count: taskCount,
          completed_task_count: completedTaskCount,
          requirement_count: requirementCount,
          requirement_completed_count: item.requirement_completed_count ?? 0,
          requirement_active_count: item.requirement_active_count ?? 0,
          requirement_pending_count: item.requirement_pending_count ?? 0,
          test_case_count: item.test_case_count ?? 0,
          defect_count: item.defect_count ?? 0,
          members,
          member_count: memberCount,
          project_manager: projectManager,
          owner_id: ownerId,
          budget: budget ?? null,
          estimated_hours: estimatedHours ?? null,
          tags,
          created_at: item.created_at,
          updated_at: item.updated_at,
          start_date: item.start_date,
          end_date: item.end_date,
          created_by: item.created_by,
          is_archived: item.is_archived || false
        }
      })

      return {
        items: standardizedItems,
        total: total
      }
    } catch (error) {
      // 解析失败时只记录错误
      if (import.meta.env.DEV) {
      console.error('解析项目列表响应时出错:', error)
      }
      return {
        items: [],
        total: 0
      }
    }
  }

  /**
   * 解析版本列表响应
   * 专门处理版本数据的解析和标准化
   * 
   * @param response - API响应对象
   * @returns 标准化的版本列表数据
   */
  static parseVersionListResponse(response: any): ParsedListResponse<any> {
    const result = this.parseListResponse(response)
    
    // 标准化版本数据格式
    result.items = result.items
      .filter((version: any) => version && version.id)
      .map((version: any) => ({
        id: version.id,
        name: version.name,
        version: version.version,
        description: version.description,
        status: version.status,
        project_id: version.project_id,
        release_date: version.release_date,
        created_by: version.created_by,
        created_at: version.created_at,
        updated_at: version.updated_at,
        is_released: version.is_released,
        release_notes: version.release_notes
      }))

    return result
  }

  /**
   * 解析缺陷列表响应
   * 专门处理缺陷数据的解析和标准化
   * 
   * @param response - API响应对象
   * @returns 标准化的缺陷列表数据
   */
  static parseDefectListResponse(response: any): ParsedListResponse<any> {
    const result = this.parseListResponse(response)
    
    // 标准化缺陷数据格式
    result.items = result.items
      .filter((defect: any) => defect && defect.id)
      .map((defect: any) => ({
        id: defect.id || defect._id,
        title: defect.title,
        description: defect.description,
        status: defect.status,
        priority: defect.priority,
        severity: defect.severity,
        type: defect.type,
        source: defect.source,
        project_id: defect.project_id,
        project_name: defect.project_name || defect.project?.name,
        assignee_id: defect.assignee_id,
        assignee_name: defect.assignee_name || defect.assignee?.name,
        reporter_id: defect.reporter_id,
        reporter_name: defect.reporter_name || defect.reporter?.name,
        verifier_id: defect.verifier_id,
        verifier_name: defect.verifier_name || defect.verifier?.name,
        version_id: defect.version_id,
        version_name: defect.version_name,
        version_number: defect.version_number,
        environment_info: defect.environment_info,
        steps_to_reproduce: defect.steps_to_reproduce,
        expected_result: defect.expected_result,
        actual_result: defect.actual_result,
        found_date: defect.found_date,
        resolved_date: defect.resolved_date,
        verified_date: defect.verified_date,
        created_at: defect.created_at,
        updated_at: defect.updated_at,
        created_by: defect.created_by,
        tags: defect.tags || [],
        attachments: defect.attachments || [],
        comments: defect.comments || [],
        comment_count: defect.comment_count || (defect.comments?.length || 0),
        attachment_count: defect.attachment_count || (defect.attachments?.length || 0)
      }))

    console.log('ResponseParser.parseDefectListResponse - 处理后的缺陷数据:', result.items.length)
    
    return result
  }

  /**
   * 解析任务列表响应
   * 专门处理任务数据的解析和标准化
   * 
   * @param response - API响应对象
   * @returns 标准化的任务列表数据
   */
  static parseTaskListResponse(response: any): ParsedListResponse<any> {
    const result = this.parseListResponse(response)
    
    // 标准化任务数据格式
    result.items = result.items
      .filter((task: any) => task && task.id)
      .map((task: any) => ({
        id: task.id,
        title: task.title,
        description: task.description,
        status: task.status,
        priority: task.priority,
        task_type: task.task_type || task.type, // 兼容后端返回的 type 字段
        type: task.type || task.task_type, // 保留 type 字段以兼容
        project_id: task.project_id,
        project_name: task.project_name, // 添加项目名称
        assignee_id: task.assignee_id,
        assignee_name: task.assignee_name, // 添加负责人名称
        assignee_avatar: task.assignee_avatar, // 添加负责人头像
        reporter_id: task.reporter_id,
        reporter_name: task.reporter_name, // 添加报告人名称
        created_by: task.created_by,
        creator_name: task.creator_name, // 添加创建人名称
        creator_avatar: task.creator_avatar, // 添加创建人头像
        estimated_hours: task.estimated_hours,
        actual_hours: task.actual_hours,
        start_date: task.start_date,
        due_date: task.due_date,
        progress: task.progress || 0, // 确保 progress 有默认值
        is_overdue: task.is_overdue, // 添加是否逾期
        created_at: task.created_at,
        updated_at: task.updated_at,
        completed_at: task.completed_at,
        tags: task.tags || [],
        attachments: task.attachments || [],
        subtasks: task.subtasks || [],
        dependencies: task.dependencies || [],
        comment_count: task.comment_count || 0, // 添加评论数
        attachment_count: task.attachment_count || 0, // 添加附件数
        total_time_spent: task.total_time_spent || 0, // 添加总工时
        version_id: task.version_id, // 添加版本ID
        version_name: task.version_name, // 添加版本名称
        version_number: task.version_number // 添加版本号
      }))

    return result
  }

  /**
   * 解析需求列表响应
   * 专门处理需求数据的解析和标准化
   * 
   * @param response - API响应对象
   * @returns 标准化的需求列表数据
   */
  static parseRequirementListResponse(response: any): ParsedListResponse<any> {
    const result = this.parseListResponse(response)
    
    // 标准化需求数据格式
    result.items = result.items
      .filter((requirement: any) => requirement && (requirement.id || requirement._id || requirement.requirement_id))
      .map((requirement: any) => {
        const requirementId =
          requirement.id ||
          requirement._id ||
          requirement.requirement_id ||
          requirement.requirementId ||
          ''

        return {
        id: requirementId,
        title: requirement.title ?? requirement.name ?? '',
        description: requirement.description || requirement.desc || '',
        requirement_type:
          requirement.requirement_type ||
          requirement.type ||
          requirement.requirementType ||
          '',
        status: requirement.status || requirement.state || requirement.status_code || '',
        priority: requirement.priority || requirement.priority_code || '',
        source: requirement.source || requirement.source_type || '',
        project_id:
          requirement.project_id ||
          requirement.projectId ||
          requirement.project?.id ||
          requirement.project?._id ||
          '',
        project_name:
          requirement.project_name ||
          requirement.projectName ||
          requirement.project?.name ||
          requirement.project?.project_name ||
          '',
        assignee_id:
          requirement.assignee_id ||
          requirement.assigneeId ||
          requirement.assignee?._id ||
          requirement.assignee?.id ||
          '',
        assignee_name:
          requirement.assignee_name ||
          requirement.assigneeName ||
          requirement.assignee?.name ||
          requirement.assignee?.full_name ||
          '',
        reporter_id:
          requirement.reporter_id ||
          requirement.reporterId ||
          requirement.reporter?._id ||
          requirement.reporter?.id ||
          '',
        reporter_name:
          requirement.reporter_name ||
          requirement.reporterName ||
          requirement.reporter?.name ||
          requirement.reporter?.full_name ||
          '',
        acceptance_criteria: requirement.acceptance_criteria || '',
        business_value: requirement.business_value || '',
        estimated_effort:
          requirement.estimated_effort ||
          requirement.effort_estimate ||
          requirement.estimatedEffort ||
          null,
        actual_effort: requirement.actual_effort || requirement.actualEffort || null,
        start_date:
          requirement.start_date ||
          requirement.startDate ||
          requirement.start_time ||
          requirement.startTime ||
          '',
        due_date:
          requirement.due_date ||
          requirement.dueDate ||
          requirement.due_time ||
          requirement.dueTime ||
          '',
        tags: Array.isArray(requirement.tags)
          ? requirement.tags
          : typeof requirement.tags === 'string'
          ? requirement.tags.split(',').map((tag: string) => tag.trim()).filter(Boolean)
          : [],
        dependencies: requirement.dependencies || [],
        watchers: requirement.watchers || [],
        versions: Array.isArray(requirement.versions)
          ? requirement.versions.map((version: any) =>
              typeof version === 'string'
                ? { id: version, name: version }
                : {
                    id: version.id || version._id || '',
                    name: version.name || version.version_name || version.version_number || '',
                    version_number: version.version_number || version.code || ''
                  }
            )
          : [],
        children: requirement.children || [],
        created_at: requirement.created_at || requirement.createdAt || requirement.created_time || '',
        updated_at: requirement.updated_at || requirement.updatedAt || requirement.updated_time || '',
        approved_at: requirement.approved_at || requirement.approvedAt || '',
        implemented_at: requirement.implemented_at || requirement.implementedAt || '',
        is_overdue: requirement.is_overdue || false,
        progress: requirement.progress || 0,
        related_tasks_count: requirement.related_tasks_count || 0,
        completed_tasks_count: requirement.completed_tasks_count || 0,
        parent_id: requirement.parent_id || requirement.parentId || null,
        children_count: requirement.children_count ?? requirement.childrenCount ?? 0
        }
      })

    return result
  }


  /**
   * 解析状态列表响应数据
   * 支持新的统一响应格式和旧格式的兼容
   * 
   * @param response - API响应对象
   * @returns 标准化的状态列表数据格式
   */
  static parseStateListResponse(response: any): ParsedListResponse<any> {
    // 处理统一响应格式
    if (response && typeof response === 'object' && 'success' in response) {
      if (response.success && response.data) {
        const data = response.data
        
        // 新格式1：data直接是数组，pagination在顶级
        if (Array.isArray(data) && response.pagination) {
          return {
            items: data,
            total: response.pagination.total || data.length,
            page: response.pagination.page,
            size: response.pagination.size,
            pagination: response.pagination
          }
        }
        
        // 新格式2：{ items: [], total: number }
        if (data.items && Array.isArray(data.items)) {
          return {
            items: data.items,
            total: data.total || data.items.length,
            pagination: data.pagination
          }
        }
        
        // 兼容旧格式：{ states: [] }
        if (data.states && Array.isArray(data.states)) {
          return {
            items: data.states,
            total: data.states.length
          }
        }
      }
    }
    
    // 兼容直接返回数据的旧格式
    if (response && typeof response === 'object') {
      // 格式：{ states: [] }
      if (response.states && Array.isArray(response.states)) {
        return {
          items: response.states,
          total: response.states.length
        }
      }
      
      // 格式：{ items: [], total: number }
      if (response.items && Array.isArray(response.items)) {
        return {
          items: response.items,
          total: response.total || response.items.length
        }
      }
    }
    
    // 直接是数组格式
    if (Array.isArray(response)) {
      return {
        items: response,
        total: response.length
      }
    }
    
    return { items: [], total: 0 }
  }

  /**
   * 解析模块状态响应数据
   * 
   * @param response - API响应对象
   * @returns 标准化的模块状态数据格式
   */
  static parseModuleStateResponse(response: any): {
    module_type: string
    states: any[]
    transitions: any[]
    initial_state?: any
    final_states: any[]
    default_state?: any
    state_count: number
    transition_count: number
    active_state_count: number
  } {
    let data = response
    
    // 处理统一响应格式
    if (response && typeof response === 'object' && 'success' in response) {
      if (response.success && response.data) {
        data = response.data
      }
    }
    
    // 确保返回标准格式
    return {
      module_type: data.module_type || '',
      states: data.states || [],
      transitions: data.transitions || [],
      initial_state: data.initial_state,
      final_states: data.final_states || [],
      default_state: data.default_state,
      state_count: data.state_count || data.states?.length || 0,
      transition_count: data.transition_count || data.transitions?.length || 0,
      active_state_count: data.active_state_count || 0
    }
  }

  /**
   * 解析状态操作响应数据
   * 
   * @param response - API响应对象
   * @returns 标准化的状态操作结果数据格式
   */
  static parseStateOperationResponse(response: any): {
    module_type?: string
    created_states?: number
    created_transitions?: number
    deleted_states?: number
    deleted_transitions?: number
    message?: string
  } {
    let data = response
    let message = ''
    
    // 处理统一响应格式
    if (response && typeof response === 'object' && 'success' in response) {
      message = response.message || ''
      if (response.success && response.data) {
        data = response.data
      }
    }
    
    return {
      module_type: data.module_type,
      created_states: data.created_states,
      created_transitions: data.created_transitions,
      deleted_states: data.deleted_states,
      deleted_transitions: data.deleted_transitions,
      message: message || data.message
    }
  }

  /**
   * 解析模块状态初始化情况响应数据
   * 
   * @param response - API响应对象
   * @returns 模块状态初始化数据
   */
  static parseModuleStatusResponse(response: any): any {
    // 处理统一响应格式
    if (response && typeof response === 'object' && 'success' in response) {
      if (response.success && response.data) {
        return response.data
      }
    }
    
    return response
  }

  /**
   * 通用错误处理方法
   * 
   * @param error - 错误对象
   * @param defaultMessage - 默认错误消息
   * @returns 标准化的错误响应
   */
  static handleError(error: any, defaultMessage: string = '操作失败'): ParsedResponse<null> {
    let message = defaultMessage
    
    if (error?.response?.data?.message) {
      message = error.response.data.message
    } else if (error?.message) {
      message = error.message
    } else if (typeof error === 'string') {
      message = error
    }
    
    return {
      data: null,
      success: false,
      message
    }
  }

  /**
   * 检查响应是否成功
   * 
   * @param response - API响应对象
   * @returns 是否成功
   */
  static isSuccess(response: any): boolean {
    const data = response?.data || response
    return data?.success === true || (response?.status >= 200 && response?.status < 300)
  }

  /**
   * 提取响应消息
   * 
   * @param response - API响应对象
   * @returns 响应消息
   */
  static extractMessage(response: any): string {
    const data = response?.data || response
    return data?.message || data?.msg || '操作完成'
  }
}

export default ResponseParser